package com.seari.crt;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.seari.bean.BaseClient;
import com.seari.crt.handler.CRTDecoder;
import com.seari.crt.handler.CRTHandler;
import com.seari.line17.Line17Client;
import com.seari.line17.handler.Line17Decoder;
import com.seari.line17.handler.Line17Handler;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import io.netty.util.concurrent.GenericFutureListener;
import java.nio.charset.Charset;

/**
 * @author yyw
 *
 */
public class CRTClient extends BaseClient {

	private static Logger logger = LoggerFactory.getLogger(CRTClient.class);

	public CRTClient() {
		super();
	}

	public CRTClient(String host, int port) {
		this.host = host;
		this.port = port;
	}

	@Override
	public void setup() throws InterruptedException {
		EventLoopGroup workGroup = new NioEventLoopGroup();
		CRTClient client = this;
		try {
			Bootstrap b = new Bootstrap();
			b.group(workGroup);
			b.channel(NioSocketChannel.class);
			b.option(ChannelOption.SO_KEEPALIVE, true);
			b.handler(new ChannelInitializer<SocketChannel>() {

				@Override
				public void initChannel(SocketChannel ch) throws Exception {
					
					logger.info("正在连接中……");
					// 字符解码器
					ByteBuf delimiter = Unpooled.copiedBuffer(CrtHelper.CRT_DELIMETER);
                                        ch.pipeline().addLast(new FixedLengthFrameDecoder(332));
					ch.pipeline().addLast("delimiterDecoder", new  DelimiterBasedFrameDecoder(2048, delimiter));
					ch.pipeline().addLast("CRTDecoder", new CRTDecoder());
					ch.pipeline().addLast("CRTHandler", new CRTHandler(client));
				}

			});

			ChannelFuture f = b.connect(host, port).sync();
			channel = f.channel();
			if (f.isSuccess()) {
				logger.info("连接成功");
			}
			f.channel().closeFuture().addListener(new GenericFutureListener<ChannelFuture>() {
				@Override
				public void operationComplete(ChannelFuture f) throws Exception {
					workGroup.shutdownGracefully();
				}
			});
		} catch (Exception e) {
			logger.warn(e.getMessage());
		}
	}
	
	
	@Override
	public void reset() throws Exception {
		if (null != channel) {
			channel.close();
		}
		setup();
	}

}
